package com.gs.process.core.interceptor;

import com.gs.process.core.user.ProcessUserService;
import com.shallowUniverse.utils.AssertUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: Shuai Guo
 * @description:
 * @date: 2021/9/27
 * @version: 1.0
 */
public class ProcessContextManager {

    private final List<ProcessInterceptor> processInterceptors = new ArrayList<>();

    private final List<ProcessPermissionInterceptor> processPermissionInterceptors = new ArrayList<>();

    private ProcessUserService processUserService;

    public ProcessContextManager(ProcessUserService processUserService) {
        this.processUserService = processUserService;
    }

    public void addInterceptor(ProcessInterceptor interceptor) {
        this.processInterceptors.add(interceptor);
    }

    public void addInterceptor(ProcessPermissionInterceptor interceptor) {
        this.processPermissionInterceptors.add(interceptor);
    }

    public List<ProcessInterceptor> getProcessInterceptors() {
        return processInterceptors;
    }

    public List<ProcessPermissionInterceptor> getProcessPermissionInterceptors() {
        return processPermissionInterceptors;
    }

    protected void autoWriedUser() {
        //执行前置处理器
        if (!CollectionUtils.isEmpty(processInterceptors)) {
            //拿到当前线程请求
            processInterceptors.forEach(processInterceptor -> processInterceptor.beforeExecuteProcessor(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest()));
        }
        //校验当前用户是否设置完毕
        AssertUtil.service().notEmpty(processUserService.get(), "请设置当前用户");
    }
}
